<script setup name="UserPassword">
import { ref } from 'vue'
import { userUpdatePasswordService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
const userStore = useUserStore()
const router = useRouter()
const formRef = ref()
const defaultModel = {
  old_pwd: '',
  new_pwd: '',
  re_pwd: '',
}
const formModel = ref({ ...defaultModel })
const rules = {
  old_pwd: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  new_pwd: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  re_pwd: [
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.new_pwd) {
          callback(new Error('两次密码不一致！'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
    { required: true, message: '内容不能为空', trigger: 'blur' },
  ],
}

const onSubmit = async () => {
  await formRef.value.validate()
  await userUpdatePasswordService(formModel.value)
  ElMessage.success('修改成功~')
  userStore.setToken('')
  userStore.setUser({})
  router.replace('/login')
}
const onReset = () => {
  formModel.value = { ...defaultModel }
}
</script>

<template>
  <page-container title="重置密码">
    <el-row>
      <el-col :span="12">
        <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px" size="large">
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="formModel.old_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="formModel.new_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="re_pwd">
            <el-input v-model="formModel.re_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" @click="onSubmit">修改密码</el-button>
            <el-button type="info" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>

<style scoped></style>
